<template>
  <div class="full">
    <div class="flex-container">
      <img src="../assets/地球.png" width="40" height="40" />
      <div class="top-title">事件调度态势</div>
      <div class="right-top">
        <div class="selectplanb">{{ this.currentMonth }}月</div>
        <!-- <select
          class="select1"
          v-model="selectedMonth"
          @change="getdata"
          @click="showOptions"
        >
          <option class="f1" value="" disabled selected>选择月份</option>
          <option v-for="month in months" :key="month">{{ month }}</option>
        </select> -->
      </div>
    </div>
    <div class="container">
      <div class="full-secondtitle">
        <div class="h1">事件调度概况</div>
      </div>
    </div>
    <div class="box">
      <div class="flex-container">
        <div class="flex-item">
          <!-- 数字 -->
          <span class="number">{{ all }}</span>
          <!-- 文字 -->
          <span class="text">{{ text1 }}事件总数</span>
        </div>

        <div class="flex-item">
          <!-- 数字 -->
          <span class="number">{{ cunn }}</span>
          <!-- 文字 -->
          <span class="text">{{ text3 }}村内事件</span>
        </div>
        <div class="flex-item">
          <div>
            <!-- 数字 -->
            <span class="number">{{ rate }}</span>
            <span class="text">%</span>
            <!-- 文字 -->
          </div>
          <span class="text">{{ text2 }}结办率</span>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="full-secondtitle">
        <div class="h1">事件类型占比</div>
      </div>
    </div>

    <div class="flex-container">
      <div class="cht2">
        <v-chart id="chart2" ref="chart2" class="chart2" :option="option2" />
      </div>
    </div>
    <div class="container">
      <div class="full-secondtitle">
        <div class="h1">事件来源分布</div>
      </div>
    </div>
    <div class="cht1">
      <v-chart id="chart1" ref="chart1" class="chart1" :option="option1" />
    </div>
    <div class="container">
      <div class="full-secondtitle">
        <div class="h1">近一年时间调度走势</div>
      </div>
    </div>
    <div class="cht3">
      <v-chart id="chart3" class="chart3" :option="option3" />
    </div>
  </div>
</template>

<script >
// var chartDom = document.getElementById("main");postall
// var myChart = echarts.init(chartDom);
import * as echarts from "echarts";
import { ref, onMounted, watch, computed } from "vue";
import axios from "axios";
import { getarticle } from "../reqeust/index";
export default {
  data() {
    return {
      // isMonthSelectorVisible: false,
      // selectedMonth: "1月",
      // start: "",
      // end: "",
      monthss: [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ],
      months: [],
      months2: [],
      currentMonth: "",
      all: 0,
      cunn: 0,
      rate: 0,
      rate1: 0,
      number1: "0",
      yearmouth: "0",
      // option1: {}, // 存储echarts图表的配置项
      option3: {}, // 存储echarts图表的配置项
      a1: {},
      a2: {},
      a3: {},
      r1: {},
      // result: [],
    };
  },
  setup() {
    const chart1 = ref(null);
    const option1 = ref(null);
    const chart2 = ref(null);
    const option2 = ref(null);
    const selectedMonth = ref("");
    const start = ref("");
    const end = ref("");
    const result = ref([]);
    const data = ref([]);
    const alltype = ref([]);
    const alltypes = ref([]);
    // 获取数据
    const today = new Date(); // 获取当前日期
    const year = today.getFullYear(); // 获取去年的年份
    const currentMonth = today.getMonth();
    const targetDate1 = new Date(year, currentMonth, 1); // 构造目标日期对象
    const targetDate2 = new Date(year, currentMonth + 1, 0);
    start.value = targetDate1.getTime(); // 获取目标日期的时间戳
    end.value = targetDate2.getTime();
    async function fetchData() {
      try {
        const response = await axios.get(
          "http://bolincun.xinpanmen.com:9002/bigscreen_source"
          // {
          //   start: start.value,
          //   end: end.value,
          // }
        );
        data.value = response.data.list;
        result.value = data.value.map((item) => {
          return { value: item.count, name: item.auth };
        });
        console.log(
          "998",
          result,
          result.value,
          data,
          data.value,
          response.data.list
        );

        // 根据接口数据生成echarts配置项bigscreen_source
        alltype.value = await axios.get(
          "http://bolincun.xinpanmen.com:9002/bigscreen_type"
          // {
          //   start: "start.value",
          //   end: "end.value",
          // }
        );
        alltypes.value = alltype.value.data.list.map((item) => {
          return { value: item.count, name: item.ctype };
        });
        let alltypenumbers = 0;
        for (let i = 0; i < alltypes.value.length; i++) {
          if (alltypes.value[i].value) {
            alltypenumbers = alltypenumbers + alltypes.value[i].value;
          }
        }
        option2.value = {
          tooltip: {},
          legend: { show: false },
          grid: {
            top: "0%",
            left: "0%",
            right: "0%",
            bottom: "43%",
          },
          xAxis: { show: false, type: "value", max: alltypenumbers },
          yAxis: { show: false, type: "category" },
          series: [],
        };
        const newDataArray = alltypes.value.map((item) => {
          return [item];
        });
        for (let i = 0; i < alltypes.value.length; i++) {
          if (alltypes.value[i].value) {
            option2.value.series.push({
              name: newDataArray[i].name,
              type: "bar",
              stack: "total",
              label: {
                show: true,
                fontSize: 16,
                fontWeight: "bold",
                formatter: function (params) {
                  var percent = ((params.value / alltypenumbers) * 100).toFixed(
                    0
                  );
                  return percent + "%" + "\n" + params.name;
                },
              },
              emphasis: {
                focus: "series",
              },
              data: newDataArray[i],
            });
          }
        }
        console.log("all", newDataArray, alltypenumbers, alltypes.value);
        option1.value = {
          // 根据需要配置echarts的option
          backgroundColor: "transparent",
          color: ["#03ae47", "#ba2822", "#e62f29"],
          tooltip: {
            trigger: "item",
            textStyle: {
              fontSize: 16, // 设置图例文字大小
            },
          },
          series: [
            {
              name: "事件来源",
              type: "pie",
              radius: [35, 55],
              // roseType: "radius",
              data: result.value,
              label: {
                color: "#ffffff",
                // alignTo: "edge",
                formatter: function (params) {
                  var percent = (
                    (params.value / data.value.length) *
                    100
                  ).toFixed(0);
                  return percent + "%" + "\n" + params.name;
                },
                // minMargin: 50,
                edgeDistance: 10,
                lineHeight: 18,
                fontSize: 16,
                rich: {
                  time: {},
                },
              },
              labelLine: {
                length: 10,
                length2: 50,
              },
              // labelLayout: {
              //   // X: "50%",
              //   // align: "center",
              //   // verticalAlign: "middle",
              //   // labelRect: { x: 20, y: 20, width: 20, height: 20 },
              // },
              // labelLayout: function (params) {
              //   const isLeft = params.labelRect.x < chart1.value.getWidth() / 2;
              //   const points = params.labelLinePoints;
              //   // Update the end point.
              //   points[2][0] = isLeft
              //     ? params.labelRect.x
              //     : params.labelRect.x + params.labelRect.width;
              //   return {
              //     labelLinePoints: points,
              //   };
              // },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
      } catch (error) {
        console.error("Failed to fetch data:", error);
        setTimeout(fetchData, 1000);
      }
    }
    // 初始化echarts图表
    function initChart() {
      chart1.value = echarts.init(document.getElementById("chart1"));
      chart2.value = echarts.init(document.getElementById("chart2"));

      watch(
        option1,
        () => {
          chart1.value.setOption(option1.value);
          chart2.value.setOption(option2.value);
        },
        { deep: true }
      );
    }
    onMounted(() => {
      initChart();
      fetchData();
    });
    return {
      option1,
      option2,
      selectedMonth,
      start,
      end,
      result,
      data,
      alltype,
      alltypes,
    };
  },
  async mounted() {
    const article = await getarticle();
    const allinfo = await axios.get(
      "http://bolincun.xinpanmen.com:9002/bigscreen_total"
      // {
      //   start: "start.value",
      //   end: "end.value",
      // }
    );

    this.all = allinfo.data.total;
    this.cunn = allinfo.data.town;
    this.rate = allinfo.data.finishrate;

    this.getDataFromAPI(); // 调用接口获取数据
    const today = new Date(); // 获取当前日期
    const year = today.getFullYear(); // 获取去年的年份
    const currentMonth = today.getMonth();
    const targetDate1 = new Date(year, currentMonth, 1); // 构造目标日期对象
    const targetDate2 = new Date(year, currentMonth + 1, 0);
    this.start = targetDate1.getTime(); // 获取目标日期的时间戳
    this.end = targetDate2.getTime();
    const yearmouth = `${year}-${currentMonth + 1}`;
    console.log("aaa", yearmouth);
    window.getdata = (data) => {
      // 执行getdata函数逻辑
      console.log(data);
    };
  },
  methods: {
    getMonthName(monthd) {
      const monthNames = [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ];
      return monthNames[monthd];
    },
    getdata() {
      const monthNames = [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ];
      const inputMonthIndex = monthNames.findIndex(
        (month) => month === this.selectedMonth
      );
      console.log(
        "b",
        inputMonthIndex,
        this.selectedMonth,
        this.currentMonth,
        new Date().setMonth(inputMonthIndex, 1)
      );
      if (inputMonthIndex > this.currentMonth) {
        const today = new Date(); // 获取当前日期
        const year = today.getFullYear() - 1; // 获取去年的年份
        const targetDate1 = new Date(year, inputMonthIndex, 1); // 构造目标日期对象
        const targetDate2 = new Date(year, inputMonthIndex + 1, 0);
        this.start = targetDate1.getTime(); // 获取目标日期的时间戳
        this.end = targetDate2.getTime();
        const yearmouth = `${year - 1}-${inputMonthIndex}`;
        console.log("1111", this.start, this.end, yearmouth);
      } else {
        const today = new Date(); // 获取当前日期
        const year = today.getFullYear();
        const yearmouth = `${year}-${inputMonthIndex + 1}`;
        this.start =
          inputMonthIndex >= 0 ? new Date().setMonth(inputMonthIndex, 1) : null;
        this.end =
          inputMonthIndex >= 0
            ? new Date().setMonth(inputMonthIndex + 1, 0)
            : null;
        console.log("22", this.start, this.end, yearmouth);
        this.yearmouth = yearmouth;
      }
      window.getdata(this.yearmouth);
    },
    showOptions() {
      if (this.selectedMonth === "") {
        this.selectedMonth = this.monthss[0];
      }
      console.log(this.selectedMonth);
    },
    async getDataFromAPI() {
      try {
        const currentDate = new Date();
        const currentMonth = currentDate.getMonth();
        this.currentMonth = currentMonth + 1; // 获取当前月份
        this.selectedMonth = this.getMonthName(currentMonth); //当前选择月分
        for (let i = 0; i < 12; i++) {
          const monthd = (currentMonth - i + 12) % 12;
          const monthName = this.getMonthName(monthd);
          this.months.push(monthName);
          console.log("a", monthName, this.months);
        }
        const monthArray = Object.values(this.months); //获取最近一年月份
        console.log("b", monthArray);
        let sortedMonths = monthArray.reverse(); //最近一年月份倒叙
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1; // 获取当前月份
        const startOfMonth = new Date(year, month - 1, 1).getTime();
        const endOfMonth = new Date(year, month, 0).getTime();
        //获取长三角的时间数组参数
        const yearMonthArray = [];
        const currentDates = new Date(year, month);
        for (let i = 0; i < 12; i++) {
          currentDates.setMonth(currentDates.getMonth() - 1);
          const year1 = currentDates.getFullYear();
          const month1 = currentDates.getMonth() + 1; // 月份需要加一，因为月份从0开始计数
          yearMonthArray.unshift(
            `${year1}-${month1 < 10 ? "0" + month1 : month1}`
          );
        }
        console.log("aaa", yearMonthArray);
        //获取村内事件的时间数组参数
        let timestampRanges1 = [];
        let timestampRanges2 = [];
        for (let i = 0; i < 12; i++) {
          // 获取每个月份的时间戳范围
          if (month > i) {
            const start = new Date(year, i, 1).getTime();
            const end =
              new Date(year, i + 1, 0).getTime() + 24 * 60 * 60 * 1000 - 1;
            // 将近一年每个月份的时间戳范围添加到数组中
            timestampRanges1.push({ start, end });
          } else {
            const start = new Date(year - 1, i, 1).getTime();
            const end =
              new Date(year - 1, i + 1, 0).getTime() + 24 * 60 * 60 * 1000 - 1;
            // 将近一年每个月份的时间戳范围添加到数组中
            timestampRanges2.push({ start, end });
          }
        }
        // 输出月份时间戳范围数组
        timestampRanges1.unshift(...timestampRanges2);
        console.log("666", timestampRanges1);
        let timestamp1 = [];
        let timestamp2 = [];
        const allyearinfo = await axios.get(
          "http://bolincun.xinpanmen.com:9002/bigscreen_year"
          // {
          //   start: "start.value",
          //   end: "end.value",
          // }
        );
        const originalArray = allyearinfo.data.list;
        // 将数组转换成两个数组
        timestamp1 = originalArray.map((item) => item.count);
        timestamp2 = originalArray.map((item) => item.finishrate);

        this.option3 = {
          backgroundColor: "transparent",
          color: ["#3fb1e3", "rgb(255, 152, 48)"],
          tooltip: {
            trigger: "axis",
            textStyle: {
              fontSize: 16, // 设置图例文字大小
            },
            axisPointer: {
              type: "cross",
              crossStyle: {
                color: "#999",
              },
            },
          },
          grid: {
            top: "18%",
            left: "10%",
            bottom: "10%",
            tooltip: {
              axisPointer: {
                label: {
                  fontSize: 16,
                },
              },
            },
          },
          legend: {
            right: "20%",
            itemWidth: 16,
            itemHeight: 10,
            textStyle: {
              fontSize: 16,
              color: "#ffffff", // 设置图例文字大小
            },
            data: ["事件总数", "完成率%"],
          },
          xAxis: [
            {
              type: "category",
              data: sortedMonths,
              axisPointer: {
                type: "shadow",
              },
              nameTextStyle: {
                fontSize: 16,
              },
              axisLabel: {
                interval: 0,
                fontSize: 16,
                color: "#ffffff", // 设置图例文字大小
              },
              axisTick: {
                show: false,
              },
            },
          ],
          yAxis: [
            {
              type: "value",
              name: "件",
              min: 0,
              // max: 100,
              interval: 1,
              nameTextStyle: {
                fontSize: 16,
                color: "#ffffff", // 设置图例文字大
                align: "right",
              },
              axisLine: {
                show: true,
                lineStyle: {
                  width: 1,
                },
              },
              axisLabel: {
                hideOverlap: true,
                interval: 0,
                fontSize: 16,
                formatter: "{value} ",
                color: "#ffffff", // 设置图例文字大小
              },
              splitLine: {
                show: false, // 不显示网格线
              },
            },
            {
              type: "value",
              name: "完成率%",
              min: 0,
              // max: 25,
              interval: 5,
              axisLabel: {
                interval: 0,
                fontSize: 16,
                formatter: "{value} %",
                color: "#ffffff",
              },
              show: false,
              nameTextStyle: {
                fontSize: 16,
                color: "#ffffff",
              },
              splitLine: {
                show: false, // 不显示网格线
              },
            },
          ],
          series: [
            {
              name: "事件总数",
              type: "bar",
              tooltip: {
                valueFormatter: function (value) {
                  return value + " 件";
                },
              },
              label: {
                show: true,
                position: "top",
                itemWidth: 8,
                itemHeight: 5,
                textStyle: {
                  fontSize: 16,
                  color: "#ffffff", // 设置图例文字大小
                },
              },
              data: timestamp1,
            },
            {
              name: "完成率%",
              type: "line",
              yAxisIndex: 1,
              symbolSize: 2, // 设置点的大小为10
              lineStyle: {
                width: 1, // 控制折线的粗细
              },
              tooltip: {
                valueFormatter: function (value) {
                  return value + " %";
                },
              },
              label: {
                show: true,
                position: "top",
                itemWidth: 8,
                itemHeight: 5,
                textStyle: {
                  fontSize: 16,
                  color: "#ffffff", // 设置图例文字大小
                },
              },
              data: timestamp2,
            },
          ],
        };
        this.renderChart(); // 渲染图表
      } catch (error) {
        // 错误处理
        console.error(error);
      }
    },
    updateChart(newData) {
      this.option1.series[0].data = newData;
      console.log("555", this.result.value);
    },
    renderChart() {
      // const myChart1 = echarts.init(document.getElementById("chart1"), "dark"); // 初始化echarts图表
      // myChart1.setOption(this.option1); // 设置图表的配置项
      const myChart3 = echarts.init(document.getElementById("chart3"), "dark"); // 初始化echarts图表
      myChart3.setOption(this.option3); // 设置图表的配置项
    },
  },
};
</script>
<style scoped>
.full {
  display: flex;
  flex-direction: column;
  width: 25rem;
  /* background-color: #e62f29; */
}
.top-title {
  width: 14rem;
  height: 2.25rem;
  font-size: 2.25rem;

  font-weight: 600;
  color: #ffffff;
  line-height: 2rem;
  background: linear-gradient(0deg, #5677a4 0%, rgb(255, 255, 255) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-left: 1rem;
}
.container {
  display: flex;
  justify-content: space-between;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}
.full-secondtitle {
  display: flex;
  align-items: center;
  background-color: #ffffff70;
  padding: 0.3rem 1rem;
}
.full-secondtitle .h1 {
  line-height: 1;
  font-size: 1.4rem;

  font-weight: 600;
  color: #ffffff;
}
.month-selector {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  right: 10%;
}
.selectplanb {
  height: 3rem;
  width: 3.5rem;
  text-align: center;
  font-size: 1.5rem;
  border-radius: 10px;
  border: 2px solid rgb(255, 255, 255); /* 设置边框宽度和颜色为蓝色 */
  box-shadow: 0 0 2px rgb(255, 255, 255); /* 添加阴影效果 */
  font-weight: 400;
  color: #ffffff;
  line-height: 3rem;
}
.select1 {
  height: 3rem;
  width: 3.5rem;
  text-align: center;
  font-size: 1.5rem;

  font-weight: 400;
  color: #ffffff;
  line-height: 3rem;
}
.select1 option {
  background-color: transparent;
}
select {
  border-radius: 10px;
  border: 2px solid rgb(0, 255, 255); /* 设置边框宽度和颜色为蓝色 */
  box-shadow: 0 0 20px rgb(0, 208, 255); /* 添加阴影效果 */
  transition: border-color 0.3s, box-shadow 0.3s; /* 添加过渡效果，使改变边框和阴影时平滑过渡 */
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  color: #03ae47;
  background-color: transparent;
}
option {
  background-color: transparent;
  color: #000000;
  border: 2px solid rgb(0, 255, 255);
  box-shadow: 0 0 20px rgb(0, 208, 255);
}
select:focus {
  /* color: #000000; */
  outline: none;
}
select::-ms-expand {
  display: none;
}
select::-webkit-outer-spin-button,
select::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.right-top {
  align-self: flex-start; /* 靠右对齐 */
  margin-left: 1rem;
}
.box {
  width: 25rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.flex-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  width: 25rem;
  border: 0.08rem solid rgba(255, 255, 255, 0.575);
  padding: 0.3rem 1rem;
}
.flex-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
  /* margin: auto; */
  flex-grow: 1;
  flex-basis: 33.33%;
}
.image {
  flex-flow: 1;
}

.number {
  font-size: 2.2rem;

  font-weight: 600;
  color: #f2f1f1;
}
.text {
  font-size: 1.2rem;

  font-weight: 400;
  color: #d9d9d9;
}
.cht1 {
  width: 25rem;
  height: 10rem;
  border: 0.08rem solid rgba(255, 255, 255, 0.575);
}
.cht2 {
  margin-top: -1.2rem;
  width: 24rem;
  height: 6.7rem;
}
.cht3 {
  width: 25rem;
  height: 15rem;
  border: 0.08rem solid rgba(255, 255, 255, 0.575);
}
.chart1 {
  width: 25rem;
  height: 10rem;
}
.chart2 {
  width: 24rem;
  height: 14rem;
}

.chart3 {
  width: 25rem;
  height: 15rem;
}
</style>